package baiduface

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"time"
)

// getClient 获取默认配置的函数
func getClient() Config {
	config := Config{
		APIKey:    "Pw2RyRzR4VbP6JrOX800WGrY",
		SecretKey: "qiyQbpF2uM2bMYzhMCoLwg0jSGFj4FKq",
	}
	return config
}

// GetAccessToken 获取百度人脸识别API访问令牌
func GetAccessToken() (*TokenResponse, error) {
	// 获取配置
	config := getClient()
	
	// 构建请求参数
	params := url.Values{}
	params.Add("grant_type", "client_credentials")
	params.Add("client_id", config.APIKey)
	params.Add("client_secret", config.SecretKey)

	// 构建完整URL
	requestURL := fmt.Sprintf("https://aip.baidubce.com/oauth/2.0/token?%s", params.Encode())

	// 创建HTTP客户端，设置超时时间
	client := &http.Client{
		Timeout: 30 * time.Second,
	}

	// 发送GET请求
	resp, err := client.Get(requestURL)
	if err != nil {
		return nil, fmt.Errorf("failed to send request: %v", err)
	}
	defer resp.Body.Close()

	// 读取响应体
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("failed to read response body: %v", err)
	}

	// 解析JSON响应
	var tokenResp TokenResponse
	err = json.Unmarshal(body, &tokenResp)
	if err != nil {
		return nil, fmt.Errorf("failed to parse response JSON: %v", err)
	}

	// 检查是否有错误信息
	if tokenResp.ERROR != "" {
		return nil, fmt.Errorf("baidu API error: %s - %s", tokenResp.ERROR, tokenResp.ErrorDescription)
	}

	return &tokenResp, nil
}